package com.atguigu.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.app.BaseApp;
import com.atguigu.gmall.realtime.bean.TradeTrademarkCategoryUserRefundBean;
import com.atguigu.gmall.realtime.common.GmallConstant;
import com.atguigu.gmall.realtime.function.AsyncDimFunction;
import com.atguigu.gmall.realtime.function.DorisMapFunction;
import com.atguigu.gmall.realtime.util.DateFormatUtil;
import com.atguigu.gmall.realtime.util.DorisUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/8/14 09:58
 */
public class Dws_11_DwsTradeTrademarkCategoryUserRefundWindow extends BaseApp {
    public static void main(String[] args) {
        new Dws_11_DwsTradeTrademarkCategoryUserRefundWindow().start(
            40011,
            2,
            "Dws_11_DwsTradeTrademarkCategoryUserRefundWindow",
            GmallConstant.TOPIC_DWD_TRADE_ORDER_REFUND
        );
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> beanStream = stream
            .map(new MapFunction<String, TradeTrademarkCategoryUserRefundBean>() {
                @Override
                public TradeTrademarkCategoryUserRefundBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    HashSet<String> orderIdSet = new HashSet<>();
                    orderIdSet.add(obj.getString("order_id"));
                    
                    return TradeTrademarkCategoryUserRefundBean.builder()
                        .skuId(obj.getString("sku_id"))
                        .userId(obj.getString("user_id"))
                        .orderIdSet(orderIdSet)
                        .refundAmount(obj.getBigDecimal("refund_amount"))
                        .ts(obj.getLong("ts") * 1000)
                        .build();
                }
                
            });
        
        // 1. 从 sku_info补充 2 两个 id: 品牌和品类   只补必须的(分组需要的)
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> aggregatedStream = AsyncDataStream
            .unorderedWait(
                beanStream,
                new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public String getTableName() {
                        return "dim_sku_info";
                    }
                
                    @Override
                    public String getId(TradeTrademarkCategoryUserRefundBean bean) {
                        return bean.getSkuId();
                    }
                
                    @Override
                    public void addDim(TradeTrademarkCategoryUserRefundBean bean, JSONObject dim) {
                        bean.setTrademarkId(dim.getString("tm_id"));
                        bean.setCategory3Id(dim.getString("category3_id"));
                    
                    }
                },
                120,
                TimeUnit.SECONDS
            )
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeTrademarkCategoryUserRefundBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(bean -> bean.getCategory3Id() + bean.getUserId() + bean.getTrademarkId())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeTrademarkCategoryUserRefundBean>() {
                    @Override
                    public TradeTrademarkCategoryUserRefundBean reduce(TradeTrademarkCategoryUserRefundBean value1,
                                                                       TradeTrademarkCategoryUserRefundBean value2) throws Exception {
                        value1.setRefundAmount(value1.getRefundAmount().add(value2.getRefundAmount()));
                        value1.getOrderIdSet().addAll(value2.getOrderIdSet());  // 把 value2 的 set 的集合的元素全部存入到 value1 的 set 集合中
                    
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradeTrademarkCategoryUserRefundBean, TradeTrademarkCategoryUserRefundBean, String, TimeWindow>() {
                    @Override
                    public void process(String s,
                                        Context ctx,
                                        Iterable<TradeTrademarkCategoryUserRefundBean> elements,
                                        Collector<TradeTrademarkCategoryUserRefundBean> out) throws Exception {
                        TradeTrademarkCategoryUserRefundBean bean = elements.iterator().next();
                        bean.setStt(DateFormatUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(DateFormatUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setCurDate(DateFormatUtil.tsToDateTime(ctx.window().getStart()));
                    
                        bean.setRefundCount((long) bean.getOrderIdSet().size());
                    
                        out.collect(bean);
                    }
                }
            );
        
        // 补充其他的维度: 
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> tmStream = AsyncDataStream
            .unorderedWait(aggregatedStream,
                           new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                               @Override
                               public String getTableName() {
                                   return "dim_base_trademark";
                               }
            
                               @Override
                               public String getId(TradeTrademarkCategoryUserRefundBean bean) {
                                   return bean.getTrademarkId();
                               }
            
                               @Override
                               public void addDim(TradeTrademarkCategoryUserRefundBean bean,
                                                  JSONObject dim) {
                                   bean.setTrademarkName(dim.getString("tm_name"));
                               }
                           },
                           120,
                           TimeUnit.SECONDS
            );
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c3Stream = AsyncDataStream
            .unorderedWait(tmStream,
                           new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                               @Override
                               public String getTableName() {
                                   return "dim_base_category3";
                               }
            
                               @Override
                               public String getId(TradeTrademarkCategoryUserRefundBean bean) {
                                   return bean.getCategory3Id();
                               }
            
                               @Override
                               public void addDim(TradeTrademarkCategoryUserRefundBean bean,
                                                  JSONObject dim) {
                                   bean.setCategory3Name(dim.getString("name"));
                                   bean.setCategory2Id(dim.getString("category2_id"));
                               }
                           },
                           120,
                           TimeUnit.SECONDS
            );
    
        SingleOutputStreamOperator<TradeTrademarkCategoryUserRefundBean> c2Stream = AsyncDataStream
            .unorderedWait(c3Stream,
                           new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                               @Override
                               public String getTableName() {
                                   return "dim_base_category2";
                               }
            
                               @Override
                               public String getId(TradeTrademarkCategoryUserRefundBean bean) {
                                   return bean.getCategory2Id();
                               }
            
                               @Override
                               public void addDim(TradeTrademarkCategoryUserRefundBean bean,
                                                  JSONObject dim) {
                                   bean.setCategory2Name(dim.getString("name"));
                                   bean.setCategory1Id(dim.getString("category1_id"));
                               }
                           },
                           120,
                           TimeUnit.SECONDS
            );
    
        AsyncDataStream
            .unorderedWait(c2Stream,
                           new AsyncDimFunction<TradeTrademarkCategoryUserRefundBean>() {
                               @Override
                               public String getTableName() {
                                   return "dim_base_category1";
                               }
            
                               @Override
                               public String getId(TradeTrademarkCategoryUserRefundBean bean) {
                                   return bean.getCategory1Id();
                               }
            
                               @Override
                               public void addDim(TradeTrademarkCategoryUserRefundBean bean,
                                                  JSONObject dim) {
                                   bean.setCategory1Name(dim.getString("name"));
                               }
                           },
                           120,
                           TimeUnit.SECONDS
            )
            .map(new DorisMapFunction<>())
            .sinkTo(DorisUtil.getDorisSink("gmall2023.dws_trade_trademark_category_user_refund_window"));
    
    }
}
/*
交易域品牌-品类-用户粒度退单各窗口汇总表


从 Kafka 读取退单明细数据，关联与分组相关的维度信息后分组，统计各分组各窗口的订单数和订单金额，
补充与分组无关的维度信息，将数据写入 doris交易域品牌-品类-用户粒度退单各窗口汇总表

1. 数据源
    dwd 退单表
    
      不需要考虑去重, 因为 dwd 层没有 left join
      
2. 订单数统计
    思路1: 按照订单 id 分组, 使用状态, 第一个详情贡献 1 , 其他贡献 0
    
    思路2:
        1   1
        2   1
        2   1
        
        存入到一个 set 集合中: set(订单1)  当聚合完成的时候,再去查看集合的长度
        
 3. 聚和
    品牌-品类-用户粒度
    
        聚合前需要去查找 sku_info 表得到两个 id: 品牌的 id 和 3级品类
        
        
 4. 聚合后:
    再去查找其他的维度:
    
        品牌表
        3 张品类表

 */